/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
#include <iostream>
using namespace std;
#include <vector>

class Solution {
public:
    TreeNode* _bulidTree(vector<int>& inorder, vector<int>& postorder, int& posti, int inbegin, int inend)
    {
        if(inbegin > inend) return nullptr;

        TreeNode* ret = new TreeNode(postorder[posti]);
        int rooti = inbegin;
        while(inorder[rooti] != postorder[posti]){
            ++rooti;
        }

        --posti;

        //[inbegin, rooti - 1] [rooti] [rooti + 1, inend]
        ret->right = _bulidTree(inorder, postorder, posti, rooti + 1, inend);
        ret->left = _bulidTree(inorder, postorder, posti, inbegin, rooti - 1);
        return ret;
    }

    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        TreeNode* root;
        int posti = postorder.size() - 1;
        root = _bulidTree(inorder, postorder, posti, 0, inorder.size() - 1);
        return root;
    }
};
